package com.galaxy.device.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.galaxy.common.core.domain.R;
import com.galaxy.common.core.exception.ServiceException;
import com.galaxy.common.core.utils.MapstructUtils;
import com.galaxy.common.core.utils.StringUtils;
import com.galaxy.common.mybatis.core.page.PageQuery;
import com.galaxy.common.mybatis.core.page.TableDataInfo;
import com.galaxy.device.api.RemoteUserService;
import com.galaxy.device.domain.DeviceBase;
import com.galaxy.device.domain.DeviceMaintenance;
import com.galaxy.device.domain.DeviceStatus;
import com.galaxy.device.domain.bo.DeviceMaintenanceBo;
import com.galaxy.device.domain.bo.UserFeedbackBo;
import com.galaxy.device.domain.vo.DeviceMaintenanceVo;
import com.galaxy.device.mapper.DeviceBaseMapper;
import com.galaxy.device.mapper.DeviceMaintenanceMapper;
import com.galaxy.device.mapper.DeviceStatusMapper;
import com.galaxy.device.service.IDeviceMaintenanceService;
import com.galaxy.device.api.RemoteSystemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 设备维护Service业务层处理
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class DeviceMaintenanceServiceImpl implements IDeviceMaintenanceService {

    private final DeviceMaintenanceMapper baseMapper;
    private final RemoteSystemService remoteSystemService;
    private final DeviceBaseMapper deviceBaseMapper;
    private final DeviceStatusMapper deviceStatusMapper;

    private final RemoteUserService remoteUserService;


    @DS("slave")
    @Override
    public TableDataInfo<DeviceMaintenanceVo> queryPageList(DeviceMaintenanceBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DeviceMaintenance> lqw = buildQueryWrapper(bo);
        Page<DeviceMaintenanceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for(DeviceMaintenanceVo r : result.getRecords()){
            if(r.getUserId() != null){
                String userVoR = remoteSystemService.getUserInfo(r.getUserId());
                r.setUserName(userVoR);
            }
            if (r.getDeviceId() != null){
                r.setDeviceName(deviceBaseMapper.selectById(r.getDeviceId()).getDeviceName());
            }

        }
        return TableDataInfo.build(result);
    }

    @DS("slave")
    @Override
    public List<DeviceMaintenanceVo> queryList(DeviceMaintenanceBo bo) {
        LambdaQueryWrapper<DeviceMaintenance> lqw = buildQueryWrapper(bo);
        List<DeviceMaintenanceVo> deviceMaintenanceVos = baseMapper.selectVoList(lqw);
        for(DeviceMaintenanceVo r : deviceMaintenanceVos){
            if(r.getUserId() != null){
                String userVoR = remoteSystemService.getUserInfo(r.getUserId());
                r.setUserName(userVoR);
            }
            if (r.getDeviceId() != null){
                r.setDeviceName(deviceBaseMapper.selectById(r.getDeviceId()).getDeviceName());
            }
        }
        return deviceMaintenanceVos;
    }

    @DS("slave")
    @Override
    public DeviceMaintenanceVo getInfo(Long id) {
        DeviceMaintenance deviceMaintenance = baseMapper.selectById(id);
        DeviceMaintenanceVo convert = MapstructUtils.convert(deviceMaintenance, DeviceMaintenanceVo.class);
        if(convert.getUserId() != null){
            String userVoR = remoteSystemService.getUserInfo(convert.getUserId());
            convert.setUserName(userVoR);

        }
        convert.setDeviceName(deviceBaseMapper.selectById(convert.getDeviceId()).getDeviceName());
        return convert;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeviceMaintenance add(DeviceMaintenanceBo bo) {
        DeviceMaintenance deviceMaintenance = MapstructUtils.convert(bo, DeviceMaintenance.class);
        baseMapper.insert(deviceMaintenance);

        return deviceMaintenance;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeviceMaintenance update(DeviceMaintenanceBo bo) {
        DeviceMaintenance deviceMaintenance = MapstructUtils.convert(bo, DeviceMaintenance.class);
        if(deviceMaintenance != null && deviceMaintenance.getEndTime() != null && deviceMaintenance.getStatus() == 2){
            deviceStatusMapper.update(
                new LambdaUpdateWrapper<DeviceStatus>()
                    .set(DeviceStatus::getLastMaintenanceTime, deviceMaintenance.getEndTime())
                .eq(DeviceStatus::getDeviceId, deviceMaintenance.getDeviceId())
            );
        }


        if(deviceMaintenance != null && deviceMaintenance.getMaintenanceType() !=1 && deviceMaintenance.getStatus() == 1){
            UserFeedbackBo userFeedbackBo = new UserFeedbackBo();
            userFeedbackBo.setDeviceId(deviceMaintenance.getDeviceId());
            userFeedbackBo.setStatus(1);
            userFeedbackBo.setReply("感谢您的反馈，该售货机正在维护中，请耐心等待");
            remoteUserService.edit(userFeedbackBo);
            deviceBaseMapper.update(new LambdaUpdateWrapper<DeviceBase>()
                .set(DeviceBase::getStatus, 4)
                .eq(DeviceBase::getId, deviceMaintenance.getDeviceId()));
        }else if(deviceMaintenance != null && deviceMaintenance.getMaintenanceType() != 1 && deviceMaintenance.getStatus() == 2){
            UserFeedbackBo userFeedbackBo = new UserFeedbackBo();
            userFeedbackBo.setDeviceId(deviceMaintenance.getDeviceId());
            userFeedbackBo.setStatus(2);
            userFeedbackBo.setReply("感谢您的反馈，该售货机已完成维护，并再次可以使用，如有故障请及时反馈");
            remoteUserService.edit(userFeedbackBo);
            deviceBaseMapper.update(new LambdaUpdateWrapper<DeviceBase>()
                .set(DeviceBase::getStatus, 1)
                .eq(DeviceBase::getId, deviceMaintenance.getDeviceId()));
        }
        baseMapper.updateById(deviceMaintenance);
        return deviceMaintenance;
    }

    @Override
    public void delete(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            baseMapper.deleteById(id);
        }
    }

    private LambdaQueryWrapper<DeviceMaintenance> buildQueryWrapper(DeviceMaintenanceBo bo) {
        LambdaQueryWrapper<DeviceMaintenance> lqw = new LambdaQueryWrapper<>();
        lqw.eq(bo.getDeviceId() != null, DeviceMaintenance::getDeviceId, bo.getDeviceId());
        lqw.eq(bo.getUserId() != null, DeviceMaintenance::getUserId, bo.getUserId());
        lqw.eq(bo.getMaintenanceType() != null, DeviceMaintenance::getMaintenanceType, bo.getMaintenanceType());
        lqw.eq(bo.getStatus() != null, DeviceMaintenance::getStatus, bo.getStatus());
        lqw.like(StringUtils.isNotBlank(bo.getMaintenanceNo()), DeviceMaintenance::getMaintenanceNo, bo.getMaintenanceNo());
        lqw.like(StringUtils.isNotBlank(bo.getDescription()), DeviceMaintenance::getDescription, bo.getDescription());
        lqw.like(StringUtils.isNotBlank(bo.getResult()), DeviceMaintenance::getResult, bo.getResult());
        lqw.orderByDesc(DeviceMaintenance::getCreateTime);
        return lqw;
    }
}
